import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import {
  Sidebar,
  SidebarContent,
  SidebarHeader,
  SidebarMenu,
  SidebarMenuItem,
  SidebarProvider,
  SidebarTrigger,
} from '@/components/ui/sidebar';
import config from '@/config';
import { getTodayItemsCount } from '@/lib/gigaAvaliable';
import { areArraysEqualIgnoreOrder, cn } from '@/lib/utils';
import { useGigaStore } from '@/store/giga';
import { useGigaNotPersisStore } from '@/store/gigaNotPersist';
import { useVirtualizer } from '@tanstack/react-virtual';
import { CalendarArrowDown, RefreshCcw, Settings } from 'lucide-react';
import { useId } from 'react';

enum OrderDirection {
  'asc' = '升序',
  'desc' = '降序',
}

interface OrderOptions {
  categoryName: string;
}
function order(productCollectInfos: CategoryInfo[], orderOptions: OrderOptions) {
  // 获取排序方向，默认为升序
  const isDescending = orderOptions.categoryName === OrderDirection.desc;

  // 复制数组以避免修改原数组（根据需求决定是否需要）
  const sortedArray = [...productCollectInfos];

  sortedArray.sort((a, b) => {
    // 比较skuInfo字符串
    const comparison = a.categoryName.localeCompare(b.categoryName);
    // 根据排序方向调整结果
    return isDescending ? -comparison : comparison;
  });

  return sortedArray;
}

export interface CategoryInfo {
  categoryName: string;
  selected?: boolean;
  todayAvailiableCount: number;
  skuInfoCount: number;
}

type Props = {
  children?: React.ReactNode;
  className?: string;
};

export default function AvaliableLocalDiskInfo({ children, className, ...props }: Props) {
  const categoryTree = useGigaNotPersisStore((state) => state.categoryTree);
  const gigaRootDirectoryHandle = useGigaNotPersisStore((state) => state.gigaRootDirectoryHandle);
  const localDiskRefreshDuration = useGigaStore((state) => state.localDiskRefreshDuration);
  const selectedAvailableCategoryNames = useGigaNotPersisStore(
    (state) => state.selectedAvailableCategoryNames,
  );
  const currentAvailableCategoryName = useGigaNotPersisStore(
    (state) => state.currentAvailableCategoryName,
  );
  const dispatch = useGigaNotPersisStore((state) => state.dispatch);
  const gigaDispath = useGigaStore((state) => state.dispatch);
  const [categoryInfos, setCategoryInfos] = useState<CategoryInfo[]>([]);
  const virtualizerParentRef = useRef(null);
  const appCofing = useAppConfig();
  const [isfreshing, setIsfreshing] = useState(false);
  const [isSelectedAll, setIsSelectedAll] = useState(false);

  const rowVirtualizer = useVirtualizer({
    count: categoryInfos.length,
    getScrollElement: () => virtualizerParentRef.current,
    estimateSize: (i) => 32,
    overscan: 5,
  });

  const id = useId();

  // 获取被选择的目录名称
  useEffect(() => {
    const seletedCategoryNames = categoryInfos
      .filter((item) => {
        return item.selected;
      })
      .map((item) => item.categoryName);
    const oldCategoryNames = selectedAvailableCategoryNames;
    if (areArraysEqualIgnoreOrder(oldCategoryNames, seletedCategoryNames)) {
      return;
    }
    dispatch({
      type: 'update',
      update(draftState) {
        draftState.selectedAvailableCategoryNames = seletedCategoryNames;
      },
    });
  }, [categoryInfos, selectedAvailableCategoryNames]);

  const getCategoryInfos = useCallback(async () => {
    let newCategoryInfos: CategoryInfo[] = [];
    await Promise.all(
      Object.keys(categoryTree).map(async (categoryName) => {
        const todayAvailiableCount = await getTodayItemsCount(categoryName);
        newCategoryInfos.push({
          categoryName: categoryName,
          todayAvailiableCount,
          skuInfoCount: categoryTree[categoryName].length,
        });
      }),
    );

    // 进行排序
    newCategoryInfos = order(newCategoryInfos, {
      categoryName: OrderDirection.asc,
    });

    setCategoryInfos((oldCategoryInfos) => {
      // 主要是获取之前的属性
      newCategoryInfos.map((newCategoryInfo) => {
        const oldCategoryInfo = oldCategoryInfos.find((oldCategoryInfo) => {
          return oldCategoryInfo.categoryName === newCategoryInfo.categoryName;
        });
        if (oldCategoryInfo) {
          newCategoryInfo.selected = oldCategoryInfo.selected;
        }
      });
      return newCategoryInfos;
    });
  }, [categoryTree]);

  // console.log(11);

  useEffect(() => {
    const timmer = setInterval(getCategoryInfos, localDiskRefreshDuration);
    getCategoryInfos();
    return () => {
      clearInterval(timmer);
    };
  }, [getCategoryInfos, localDiskRefreshDuration]);

  return (
    <SidebarProvider
      className="w-auto relative"
      style={{
        // @ts-ignore
        '--sidebar-width': '20em',
      }}
    >
      <SidebarTrigger
        title="折叠/展开"
        className="absolute transition-[left] left-0 z-50 top-2 !cursor-pointer group-has-[[data-collapsible=offcanvas]]/sidebar-wrapper:left-[-1.6em]"
      ></SidebarTrigger>
      <div className="bd-gray rounded-lg mr-2 overflow-hidden flex">
        <div className={cn(className, 'relative')} {...props}>
          <Sidebar variant="sidebar" className="h-[100%] absolute w-full">
            <SidebarHeader className=" ">
              <div className="ml-5 flex items-center flex-row">
                <div className="text-lg mr-3 w-[100px] overflow-hidden text-ellipsis whitespace-nowrap">
                  {gigaRootDirectoryHandle ? gigaRootDirectoryHandle.name : '目录文件'}
                </div>
                <div className="ml-auto mr-3">
                  <Settings
                    className="cursor-pointer"
                    size={15}
                    onClick={() => {
                      gigaDispath({
                        type: 'update',
                        update(draftState) {
                          draftState.currentTabValue = config.gigaAvailableSettingsTabValue;
                        },
                      });
                    }}
                  ></Settings>
                </div>
                <div className="">
                  <RefreshCcw
                    size={14}
                    className="cursor-pointer transition-transform"
                    style={{
                      transform: isfreshing ? 'rotate(90deg)' : 'rotate(0deg)',
                    }}
                    onClick={async () => {
                      if (isfreshing) {
                        return;
                      }
                      setIsfreshing(true);
                      await getCategoryInfos().finally(() => {
                        setIsfreshing(false);
                      });
                    }}
                  ></RefreshCcw>
                </div>
              </div>
              <div className="flex items-center">
                <div className="flex gap-2 bd-bottom-gray items-center">
                  <Checkbox
                    checked={isSelectedAll}
                    onCheckedChange={(state) => {
                      setIsSelectedAll(state ? true : false);
                      setCategoryInfos((oldCategoryInfos) => {
                        return oldCategoryInfos.map((oldCategoryInfo) => {
                          return {
                            ...oldCategoryInfo,
                            selected: state ? true : false,
                          };
                        });
                      });
                    }}
                    id={id + '-localDiskinfo-select-info'}
                    className="rounded-[2px] mr-2 border-[#478ffc] data-[state=checked]:bg-[#478ffc] data-[state=checked]:text-primary-foreground"
                  />
                  <Label
                    className="whitespace-nowrap mb-0"
                    htmlFor={id + '-localDiskinfo-select-info'}
                  >
                    全选
                  </Label>
                </div>
                <Button
                  onClick={() => {
                    setCategoryInfos((oldCategoryInfos) => {
                      return oldCategoryInfos.map((oldCategoryInfo) => {
                        return {
                          ...oldCategoryInfo,
                          selected:
                            oldCategoryInfo.skuInfoCount !== oldCategoryInfo.todayAvailiableCount,
                        };
                      });
                    });
                  }}
                  size="sm"
                  className="hover:bg-[#337AB7] bg-[#428BCA] ml-auto"
                >
                  选择未完成
                </Button>
              </div>
            </SidebarHeader>
            <SidebarContent className="px-4" ref={virtualizerParentRef}>
              <SidebarMenu
                className="gap-0"
                style={{
                  height: `${rowVirtualizer.getTotalSize()}px`,
                  position: 'relative',
                }}
              >
                {rowVirtualizer.getVirtualItems().map((virtualRow, index) => {
                  const categoryInfo = categoryInfos[virtualRow.index];
                  return (
                    <SidebarMenuItem
                      className="flex items-center"
                      key={categoryInfo.categoryName}
                      style={{
                        height: `${virtualRow.size}px`,
                        transform: `translateY(${virtualRow.start - index * virtualRow.size}px)`,
                      }}
                    >
                      <Checkbox
                        checked={categoryInfo.selected || false}
                        onCheckedChange={(state) => {
                          setCategoryInfos((oldCategoryInfos) => {
                            return oldCategoryInfos.map((oldCategoryInfo) => {
                              if (oldCategoryInfo.categoryName === categoryInfo.categoryName) {
                                return {
                                  ...oldCategoryInfo,
                                  selected: state ? true : false,
                                };
                              }
                              return oldCategoryInfo;
                            });
                          });
                        }}
                        className="rounded-[2px] mr-2 border-[#478ffc] data-[state=checked]:bg-[#478ffc] data-[state=checked]:text-primary-foreground"
                      />
                      <div className="whitespace-nowrap flex items-center">
                        <div
                          title={`当天获取的库存数量: ${categoryInfo.todayAvailiableCount}\n总的产品数量: ${categoryInfo.skuInfoCount}\n`}
                        >
                          <CalendarArrowDown
                            size={16}
                            className={`mr-2 shrink-0 ${categoryInfo.skuInfoCount === categoryInfo.todayAvailiableCount ? 'text-blue-700' : ''}`}
                          ></CalendarArrowDown>
                        </div>
                        <div
                          onClick={() => {
                            // console.log(productCategoryInfo.categoryName);
                            dispatch({
                              type: 'update',
                              update(draftState) {
                                draftState.currentAvailableCategoryName = categoryInfo.categoryName;
                              },
                            });
                            gigaDispath({
                              type: 'update',
                              update(draftState) {
                                draftState.currentTabValue = categoryInfo.categoryName;
                              },
                            });
                          }}
                          className={`text-sm select-text cursor-pointer ${currentAvailableCategoryName === categoryInfo.categoryName ? 'text-primary' : ''}`}
                        >
                          {categoryInfo.categoryName}
                        </div>
                      </div>
                      {/* <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <SidebarMenuAction>
                            <MoreHorizontal />
                          </SidebarMenuAction>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent side="right" align="start" className="z-[10002]">
                          <DropdownMenuItem
                            className="cursor-pointer"
                            onClick={() => {
                              collect(productCollectInfo);
                            }}
                          >
                            <ArrowBigDown></ArrowBigDown>
                            <span>采集</span>
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu> */}
                    </SidebarMenuItem>
                  );
                })}
              </SidebarMenu>
            </SidebarContent>
          </Sidebar>
        </div>
      </div>
    </SidebarProvider>
  );
}
